/*================================================================*
        Copyright (C) 2021 All rights reserved, www.hsby.link.
      	�ļ����ƣ�socket.cc
      	�� �� �ߣ���ɭ����
      	�������ڣ�2022/01/01
 *================================================================*/

#include "http/http_server.h"
#include "http/http_session.h"

namespace hsby {
namespace http {

HttpServer::HttpServer(const std::string &name, bool keepalive)
            : TcpServer(name),
              is_keep_alive(keepalive),
              servlet_dispatch_(std::make_shared<ServletDispatch>()){
}

HttpServer::Ptr HttpServer::Create(const std::string &name, bool keepalive) {
    return hsby::http::HttpServer::Ptr(new HttpServer(name, keepalive));
}

bool HttpServer::Init(hsby::IoManager *worker, hsby::IoManager *io_manager, hsby::IoManager *accept_manager) {
    return TcpServer::Init(worker, io_manager, accept_manager);
}

void HttpServer::ClientHandle(Socket::Ptr client) {
    if (!client) {
        HSBY_LOG_SYSTEM_INFO << "HttpServer::ClientHandle client is null";
        return;
    }
    auto session = PtrCreator<HttpSession>()(client);
    while(session->IsConnected()) {
        auto req = session->RecvRequest();
        if (!req) {
            //HSBY_LOG_SYSTEM_DEBUG << "recv http requst fail, " << HSBY_ERROR_EXP << ", client=" << *client;
            break;
        }
        bool close = !is_keep_alive || req->GetIsClose();
        //HSBY_LOG_SYSTEM_DEBUG << HSBY_VARS_EXP(is_keep_alive, req->GetIsClose());
        auto rsp = HttpResponse::Create(req->GetVersion(), close);
//        servlet_dispatch_->HandleClient(req, rsp, session);
        rsp->SetBody("abc");
        session->SendResponse(rsp);
        if (close) {
            break;
        }
    }
    session->Close();
    //HSBY_LOG_SYSTEM_DEBUG << "On HttpServer::ClientHandle end";
}

}//namespace http
}//namespace hsby